﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace MessageRouter.ServiceBroker
{
    internal sealed class ServiceBrokerMessageReaderConnectionFactory
    {
        private readonly string connectionString;

        public ServiceBrokerMessageReaderConnectionFactory(ServiceBrokerEndpointAddress endpointAddress)
        {
            this.connectionString = GetConnectionString(endpointAddress);
        }

        public SqlConnection Create()
        {
            return new SqlConnection(this.connectionString);
        }

        private string GetConnectionString(ServiceBrokerEndpointAddress endpointAddress)
        {
            SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder();
            sqlConnectionStringBuilder.DataSource = endpointAddress.InstanceName != "MSSQLSERVER"
                ? string.Format(@"{0}\{1}", endpointAddress.ServerName, endpointAddress.InstanceName)
                : string.Format(@"{0}", endpointAddress.ServerName);
            sqlConnectionStringBuilder.InitialCatalog = endpointAddress.DatabaseName;
            sqlConnectionStringBuilder.IntegratedSecurity = true;
            sqlConnectionStringBuilder.Pooling = true;
            return sqlConnectionStringBuilder.ToString();
        }
    }
}
